package com.cet.designapplication.bizmq;

import com.cet.designapplication.pojo.Products;
import com.cet.designapplication.repo.ProductsRepository;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author NSOC
 */

@Component
public class ScoreAndRedBagSendConsumer {

    @Autowired
    private ProductsRepository productsRepository;

    @RabbitListener(queues = "deadQueue", ackMode = "MANUAL")
    public void receiveMessage(Map<String, Object> message, Channel channel, Message messages, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try
        {
            // correlationId null
            System.out.println(messages.getMessageProperties().getCorrelationId());
            System.out.println("接收者收到Map格式消息：");
            System.out.println("产品标识：" + message.get("productId"));
            System.out.println("价格：" + message.get("price"));

            BigDecimal price = (BigDecimal) message.get("price");
            String productId = (String) message.get("productId");
            int score = Math.round(price.floatValue()) / 100;
            System.out.println("延时处理,为用户更新积分! score = " + score);
            Products product = productsRepository.findByProductId(productId);
            if (product != null && product.getSendRedBag() == 1) {
                System.out.println("延时处理，为用户发送红包！ productId = " + productId);
            }
            //确认消息
            channel.basicAck(deliveryTag, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();

            //拒绝消息
            try {
                channel.basicReject(deliveryTag, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
